package zmee.common.handler;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.scm.common.constant.BillAssistConstant;
import kd.scm.pds.common.constant.SrcCommonConstant;
import kd.scm.pds.common.constant.SrcMetadataConstant;
import kd.scm.pds.common.extplugin.ExtPluginContext;
import kd.scm.pds.common.extplugin.IExtPluginHandler;

import java.util.Objects;

/**
 * 浙江物产临时插件
 * 项目启动/定标--反审核--删除已发布的公告单据关联关系
 *
 * @author rd_fucong_liu
 */
public class SrcProjectNoticeUnAuditDeleteNotice implements IExtPluginHandler {
        private static final long serialVersionUID = 1L;

        @Override
        public void process(ExtPluginContext context) {
            DynamicObject billObj = context.getBillObj();
            String billType = context.getEntryEntityId();
            QFilter qfilter = new QFilter(SrcCommonConstant.PARENTID, QCP.equals, billObj.getPkValue().toString());
            if (Objects.equals(SrcMetadataConstant.SRC_PROJECT, billType)) {
                qfilter.and(SrcCommonConstant.ENTITYKEY, QCP.equals, SrcMetadataConstant.SRC_SOURCENOTICE);
            } else if (Objects.equals(SrcMetadataConstant.SRC_DECISION, billType)) {
                qfilter.and(SrcCommonConstant.ENTITYKEY, QCP.equals, SrcMetadataConstant.SRC_DECISIONNOTICE);
            }

            // 反审核时，删除单据关联关系
            QFilter botpQfilter = new QFilter("sbillid", QCP.equals, billObj.getPkValue());
            if (Objects.equals(SrcMetadataConstant.SRC_PROJECT, billType)) {
                DynamicObject sourceNotice = QueryServiceHelper.queryOne(SrcMetadataConstant.SRC_SOURCENOTICE, "id", qfilter.toArray());
                if (Objects.isNull(sourceNotice)) {
                    return;
                }
                botpQfilter.and("tbillid", QCP.equals, sourceNotice.getLong(BillAssistConstant.ID));
            } else if (Objects.equals(SrcMetadataConstant.SRC_DECISION, billType)) {
                DynamicObject decisionNotice = QueryServiceHelper.queryOne(SrcMetadataConstant.SRC_DECISIONNOTICE, "id", qfilter.toArray());
                if (Objects.isNull(decisionNotice)) {
                    return;
                }
                botpQfilter.and("tbillid", QCP.equals, decisionNotice.getLong(BillAssistConstant.ID));
            }
            DeleteServiceHelper.delete("botp_billtracker", botpQfilter.toArray());
        }
    }